const { validationResult } = require('express-validator');
const {
    router,
    Result,
    querySql,
    queryOne
} = require('../connect');
const boom = require('boom');


router.get('/', async (req, res, next) => {
    const err = validationResult(req);
    // 如果验证出错，error不为空[]
    if (!err.isEmpty()) {
        // 获取错误信息
        const [{
            msg
            // @ts-ignore
        }] = err.errors;
        // 抛出错误，交给我们自定义的统一异常处理程序进行错误返回 
        next(boom.badRequest(msg));
        return;
    }

    const sql = `SELECT * from menu`

    const menuList = await querySql(sql)
    let result = menuList.filter(item => item.pid === 0)
    getAllChild(result)

    res.json(new Result({
        data: result,
        code: 200
    }))

    //find some item all child
    function findItemChild(item) {
        var arrayList = [];
        for (var i in menuList) {
            if (menuList[i].pid == item.id) {
                arrayList.push(menuList[i]);
            }
        }
        return arrayList;
    }
    //get all child
    function getAllChild(array) {
        var childList = findItemChild(array[0]);
        if (childList == null) {
            return [];
        }
        else {
            for (var j in childList) {
                childList[j].children = [];
                childList[j].children = getAllChild([childList[j]]);
            }
            array[0].children = childList;
        }
        return childList;

    }
})

module.exports = router;